<?php

namespace App\Http\Repositories\Relation;

use App\Http\Repositories\Demand\DemandRepo;
use App\Http\Repositories\Repository;
use App\Http\Repositories\Service\ServiceRepo;
use App\Models\UserObjectRelation;

/**
 * 用户需求/服务关联
 */
class UserObjectRepo extends Repository
{
    const MODEL = UserObjectRelation::class;

    public function search(array $params, int $type)
    {
        $query = $this->query()
            ->where("type", $type);

        if (!empty($params["origin_user_id"])) {
            $query->where("origin_user_id", $params["origin_user_id"]);
        }

        if (!empty($params["target_user_id"])) {
            $query->where("target_user_id", $params["target_user_id"]);
        }

        if ($type == config("project.user_favorities_type.service")) {
            $query->with(['services' => function ($q) {
                $q->with(['resources', 'types', "provinces", "citys", "areas"]);
            }]);
        } else {
            $query->with(['demands' => function ($q) {
                $q->with(['resources', 'types', "provinces", "citys", "areas"]);
            }]);
        }
        $query->orderBy("readed", "desc");
        $query->orderBy("id", "desc");

        return $this->paginate($query, $params["paginate"] ?? true, $params["page_num"] ?? 10);
    }

    public function check(array $params): int
    {
        $type = $params["type"] ?? 0;
        $object_id = $params["object_id"] ?? 0;
        $now = date("Y-m-d H:i:s");

        if (!in_array($type, [1, 2])) abort(422, "参数错误");

        if ($type == config("project.user_object_relation.service")) {
            $object = app(ServiceRepo::class)->query()
                ->where("deadline", ">=", $now)
                ->where("status", config("project.common_status.agree"))
                ->where("id", $object_id)
                ->first();
            if (empty($object)) abort(422, "该服务不存在");
        } elseif ($type == config("project.user_object_relation.demand")) {
            $object = app(DemandRepo::class)->query()
                ->where("deadline", ">=", $now)
                ->where("status", config("project.common_status.agree"))
                ->where("id", $object_id)
                ->first();
            if (empty($object)) abort(422, "该需求不存在");
        }

        return $object->user_id;
    }
}
